﻿using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Drawing;
using MonitorPrism_Practice.Mvvm;
using MonitorPrism_Practice.Services;
using Newtonsoft.Json.Linq;
using SCADALight.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

namespace MonitorPrism_Practice.ViewModel
{
    public class InterfacePlotViewModel : BindableBase, IViewLoadedAndUnloadedAware
    {
        #region fileds
        public ConcurrentQueue<double[]> UpdataDataQueue = new ConcurrentQueue<double[]>();
        public double[] Values = new double[3];
        private CancellationTokenSource _cancellationTokenSource;
        private readonly Dispatcher _dispatcher;
        private LogEventService _logEventService;
        private readonly object _lockObject = new object(); // 用于保护缓冲区操作
        // 防止内存溢出，平衡UI性能的缓冲区
        private readonly BlockingCollection<List<double>> _renderBuffer = new BlockingCollection<List<double>>(new ConcurrentQueue<List<double>>(), 200);
        public bool Start = false;
        public ClassLiveCharts2Line ClassLiveCharts2Line { get; set; }
        private ObservableCollection<string> _leftValues = new ObservableCollection<string>()
        {
            "100","200","300","400","500","600"
        };

        public ObservableCollection<string> LeftValues { get { return _leftValues; } set { SetProperty(ref _leftValues, value); } }

        private int _lefttselectedItem;
        public int LeftSelectedItem
        {
            get => _lefttselectedItem; set
            {
                SetProperty(ref _lefttselectedItem, value);
                int member = (int)(LeftValueRange)Enum.ToObject(typeof(LeftValueRange), _lefttselectedItem);
                ClassLiveCharts2Line.ISeries_YAxis_Normal[0].MaxLimit = member;
                ClassLiveCharts2Line.ISeries_YAxis_Normal[0].MinStep = member / 10;
                ClassLiveCharts2Line.ISeries_YAxis_MaxLimit = member;
            }
        }
        private ObservableCollection<string> _rightValues = new ObservableCollection<string>()
        {
            "500","1000","1500","2000"
        };

        public ObservableCollection<string> RightValues { get => _rightValues; set { SetProperty(ref _rightValues, value); } }
        private int _righttselectedItem;
        public int RightSelectedItem
        {
            get => _righttselectedItem; set
            {
                SetProperty(ref _righttselectedItem, value);
                int member = (int)(LeftValueRange)Enum.ToObject(typeof(LeftValueRange), _righttselectedItem);
                ClassLiveCharts2Line.ISeries_YAxis_Normal[1].MaxLimit = member;
                ClassLiveCharts2Line.ISeries_YAxis_Normal[1].MinStep = member / 10;
                ClassLiveCharts2Line.ISeries_YAxis_MaxLimitRight = member;
            }
        }
        #endregion

        private ICommand mouseLeaveCommand;
        public ICommand MouseLeaveCommand
        {
            get
            {
                return this.mouseLeaveCommand ?? (this.mouseLeaveCommand = new DelegateCommand(() => { ClassLiveCharts2Line.LiveChartsAxisReset(); }));
            }
        }

        private ICommand lineStartCommand;
        public ICommand LineStartCommand
        {
            get
            {
                return this.lineStartCommand ?? (this.lineStartCommand = new DelegateCommand(() => { Start = true; }));
            }
        }
        private ICommand lineStopCommand;
        public ICommand LineStopCommand
        {
            get
            {
                return this.lineStopCommand ?? (this.lineStopCommand = new DelegateCommand(() => { Start = false; }));
            }
        }
        private ICommand emptyLineCommand;


        public ICommand EmptyLineCommand
        {
            get
            {
                return this.emptyLineCommand ?? (this.emptyLineCommand = new DelegateCommand(() => { ClassLiveCharts2Line.List_ObservableCollectionAllClear(); }));
            }
        }


        public void UpdateSeries()
        {

        }
        public InterfacePlotViewModel(ClassLiveCharts2Line classLiveCharts2Line)
        {
            ClassLiveCharts2Line = classLiveCharts2Line;
            _dispatcher = Dispatcher.CurrentDispatcher;
            _logEventService = _logEventService = ContainerLocator.Current.Resolve<LogEventService>();
            ClassLiveCharts2Line.LiveChartsLineSeriesNameSet(new List<string> { "温度(℃)", "目标温度(℃)", "功率(W)" });

            _cancellationTokenSource = new CancellationTokenSource();
            Task.Run(async () =>
            {
                int timeDelay = 150;
                while (true)
                {
                    if (Start&& Values.Length>0)
                    {
                        await Task.Delay(timeDelay);
                        ClassLiveCharts2Line.LiveChartsStartPlot(false, Values.ToList(), 100, 2);

                    }
                    else
                    {
                        if (Start&& Values.Length <= 0)
                        {
                            _logEventService.AddItem(new LogEventModel() { Message = "数据为空，请添加图表数据....." });
                            await Task.Delay(500);
                        }
                        else
                        {
                            await Task.Delay(500);
                        }
                       
                    }


                }
            });
        }

        public async void OnLoaded(object sender, RoutedEventArgs e)
        {

        }

        public void OnUnloaded(object sender, RoutedEventArgs e)
        {

        }
        /// <summary>
        /// 清空队列
        /// </summary>
        public void StopProcessing()
        {
            Start = false;

            if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource.Dispose();
                _cancellationTokenSource = null;
            }
            while (UpdataDataQueue.TryDequeue(out _)) { }
            _renderBuffer.TryTake(out _);
        }
    }
    public class InterfacePlotEvent : PubSubEvent<InterfacePlotViewModel>
    {


    }

    public enum LeftValueRange
    {
        OneLevel = 100,
        TwoLevel = 200,
        ThreeLevel = 300,
        FourLevel = 400,
        FiveLevel = 500,
        SixLevel = 600,
    }

}
